package com.alibaba.citrus.ots.price.repository.impl;

import com.alibaba.acm.shaded.com.alibaba.metrics.StringUtils;
import com.alibaba.citrus.ots.common.annotation.RepositoryInvoker;
import com.alibaba.citrus.ots.price.ability.facade.CreditQueryServiceImpl;
import com.alibaba.citrus.ots.price.ability.functions.factory.price.process.PropertyProcessManager;
import com.alibaba.citrus.ots.price.repository.CreditQueryRepository;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.otsapplicationadaptersdk.sap.MnSapIf002ResultSDO;
import com.epoch.app.otsapplicationadaptersdk.sap.mnsapif002.dto.DoHandlerRequest;
import com.epoch.app.otsapplicationadaptersdk.sap.mnsapif002.dto.DoHandlerResponse;
import com.epoch.app.otsapplicationadaptersdk.sap.mnsapif002.service.MnSapIf002Service;
import com.epoch.app.otsplatformenhance.api.customerquery.service.CustomerQueryService;
import com.epoch.app.otsplatformenhance.api.group.scitemgroupquery.service.ScItemGroupQueryService;
import com.epoch.app.otsplatformenhance.api.organizationquery.service.OrganizationQueryService;
import com.epoch.app.otsplatformenhance.channel.service.ChannelService;
import com.epoch.app.otsplatformenhance.dto.request.CustomerRequest;
import com.epoch.app.otsplatformenhance.dto.request.QueryScItemGroupRequest;
import com.epoch.app.otsplatformenhance.dto.response.ScItemGroupResponse;
import com.epoch.app.otsplatformenhance.model.dto.ChannelResponse;
import com.epoch.app.otsplatformenhance.model.dto.QueryChannelRequest;
import com.epoch.app.otsplatformenhance.sdo.CustomerSDO;
import com.epoch.app.otspricecenter.enums.DimensionPropertyEnum;
import com.epoch.app.otspricecenter.model.dto.BatchQueryCreditRequest;
import com.epoch.app.otspricecenter.model.dto.CreditReponse;
import com.epoch.app.otspricecenter.model.dto.QueryCreditRequest;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @description:
 * @author: qianlei
 * @create: 2021/10/29 01:22
 */
@Repository
public class CreditQueryRepositoryImpl implements CreditQueryRepository {

    private static Log log = Log.getLogger(CreditQueryRepositoryImpl.class);

    @Autowired
    MnSapIf002Service mnSapIf002Service;
    @Autowired
    ScItemGroupQueryService scItemGroupQueryService;
    @Autowired
    CustomerQueryService customerQueryService;
    @Autowired
    OrganizationQueryService organizationQueryService;
    @Autowired
    ChannelService channelService;
    @Resource
    private PropertyProcessManager propertyProcessManager;

    @Override
    @RepositoryInvoker(printLog = true)
    public List<CreditReponse> queryCreditList(BatchQueryCreditRequest batchQueryCreditRequest) {
        return queryCreditList(batchQueryCreditRequest, true);
    }

    @Override
    @RepositoryInvoker(printLog = true)
    public List<CreditReponse> queryCreditList(BatchQueryCreditRequest batchQueryCreditRequest, boolean enhance) {
        try {
            DoHandlerRequest doHandlerRequest = new DoHandlerRequest();
            QueryCreditRequest queryCreditRequest = batchQueryCreditRequest.getQueryCreditRequestList().get(0);
            doHandlerRequest.setOrganizationId(queryCreditRequest.getOrganizationCode());
            doHandlerRequest.setChannelId(queryCreditRequest.getChannelCode());
            doHandlerRequest.setScItemGroupId(queryCreditRequest.getItemGroupCode());
            doHandlerRequest.setCustomerId(queryCreditRequest.getCustomerCode());
            doHandlerRequest.setSaleOrderId(queryCreditRequest.getSaleOrderId());
            //原参数模型发生改变@hanguo
            DoHandlerResponse response = mnSapIf002Service.doHandler(doHandlerRequest);
            if (response != null && response.getData() != null) {
                MnSapIf002ResultSDO sdo = response.getData();
                CreditReponse creditReponse = new CreditReponse();
                creditReponse.setOrganizationCode(queryCreditRequest.getOrganizationCode());
                creditReponse.setChannelCode(queryCreditRequest.getChannelCode());
                creditReponse.setItemGroupCode(queryCreditRequest.getItemGroupCode());
                creditReponse.setCustomerCode(queryCreditRequest.getCustomerCode());
                if (StringUtils.isNotBlank(sdo.getOBLIG()) && sdo.getOBLIG().endsWith("-")) {
                    // 特殊处理， 增加对sap负值， 负号在末位的处理
                    String dealBalance = "-" + sdo.getOBLIG().substring(0, sdo.getOBLIG().length() - 1);
                    creditReponse.setBalance(dealBalance);
                } else {
                    creditReponse.setBalance(sdo.getOBLIG());
                }

                creditReponse.setCreditFlag(sdo.getZFLAG());
                creditReponse.setRiskType(sdo.getCTLPC());
                creditReponse.setMessage(sdo.getMESSAGE());
                creditReponse.setSuccess(Objects.equals(sdo.getCODE(), 0));
                //查询对应基础资料名称
                if (enhance && StringUtils.isNotBlank(queryCreditRequest.getOrganizationCode())) {
                    //根据内部编码获取组织名称
                    Map<String, String> organizationOutCodeAndDescMap = propertyProcessManager.getPropertyProcess(
                            DimensionPropertyEnum.ORG_SALES_ORGANIZATION_CODE.getKey())
                            .obtainCodeAndDescMap(Lists.newArrayList(queryCreditRequest.getOrganizationCode()), true);
                    creditReponse.setOrganizationName(organizationOutCodeAndDescMap.get(queryCreditRequest.getOrganizationCode()));
                    //                IdQueryRequest idQueryRequest = new IdQueryRequest();
                    //                idQueryRequest.setId(queryCreditRequest.getOrganizationCode());
                    //                Result<OrganizationSDO> result = organizationQueryService.getOrganizationDetail(idQueryRequest);
                    //                if (result.isSuccess() && result.getResult() != null){
                    //                    OrganizationSDO organizationSDO = result.getResult();
                    //                    creditReponse.setOrganizationName(organizationSDO.getName());
                    //                }
                }

                if (enhance && StringUtils.isNotBlank(queryCreditRequest.getChannelCode())) {
                    QueryChannelRequest baselineBatchQueryChannelsRequest = new QueryChannelRequest();
                    baselineBatchQueryChannelsRequest.setChannelCode(queryCreditRequest.getChannelCode());
                    //调用查询渠道信息
                    Result<ChannelResponse> result = channelService.queryChannelDetail(baselineBatchQueryChannelsRequest);
                    if (result.isSuccess() && result.getResult() != null) {
                        creditReponse.setChannelName(result.getResult().getChannelName());
                    }
                }
                //调用查询货品组信息
                if (enhance && StringUtils.isNotBlank(queryCreditRequest.getItemGroupCode())) {
                    QueryScItemGroupRequest request = new QueryScItemGroupRequest();
                    request.setCode(queryCreditRequest.getItemGroupCode());
                    Result<ScItemGroupResponse> result = scItemGroupQueryService.getScItemGroup(request);
                    if (result.isSuccess() && result.getResult() != null) {
                        creditReponse.setItemGroupName(result.getResult().getName());
                    }
                }
                //调用查询客户信息
                if (enhance && StringUtils.isNotBlank(queryCreditRequest.getCustomerCode())) {
                    CustomerRequest request = new CustomerRequest();
                    request.setCode(queryCreditRequest.getCustomerCode());
                    Result<CustomerSDO> result = customerQueryService.queryCustomer(request);
                    if (result.isSuccess() && result.getResult() != null) {
                        creditReponse.setCustomerName(result.getResult().getName());
                    }
                }

                return Lists.newArrayList(creditReponse);
            } else {
                return null;
            }
        } catch (Exception e) {
            log.error("获取信贷异常", e);
        }

        return null;
    }
}
